from utils import log_debug, log_error
from dao.favorite_questions_dao import FavoriteQuestionDAO
from dao.questions_dao import QuestionDAO
from models.favorite_question import FavoriteQuestion
from models.question import Question
from typing import List


class FavoriteService:
    """收藏题目服务类，处理收藏题目相关的业务逻辑"""

    def __init__(self):
        """
        初始化FavoriteService
        :param db_path: 数据库文件路径
        """
        self.favorite_dao = FavoriteQuestionDAO()
        self.questions_dao = QuestionDAO()

    def get_favorite_questions(self, user_id: int, category: str) -> List[Question]:
        """
        根据用户ID和分类获取收藏题目
        :param user_id: 用户ID
        :param category: 题目分类
        :return: 收藏题目列表
        """
        try:
            # 获取收藏记录
            favorite_records = self.favorite_dao.get_by_user_and_category(user_id, category)
            # print(f"收藏记录类型: {type(favorite_records[0]) if favorite_records else 'None'}")
            # 获取题目ID列表
            question_ids = [record.question_id for record in favorite_records]
            # 根据ID列表获取题目对象
            questions = []
            for q_id in question_ids:
                question = self.questions_dao.get_by_id(q_id)
                if question:
                    # print(f"题目对象类型: {type(question)}")
                    questions.append(question)
            log_debug(f"获取用户{user_id}分类{category}的收藏题目成功，共{len(questions)}条记录")
            return questions
        except Exception as e:
            log_error(f"获取收藏题目时发生错误: {e}")
            return []

    def add_favorite_question(self, user_id: int, question_id: int, category: str) -> bool:
        """
        添加收藏题目
        :param user_id: 用户ID
        :param question_id: 题目ID
        :param category: 题目分类
        :return: 添加成功返回True，否则返回False
        """
        try:
            # 检查是否已经收藏
            existing = self.favorite_dao.get_by_user_and_question(user_id, question_id)
            if existing:
                log_debug(f"用户{user_id}已经收藏了题目{question_id}")
                return False
            # 创建新的收藏记录
            new_favorite = FavoriteQuestion(
                user_id=user_id,
                question_id=question_id,
                category=category
            )
            result = self.favorite_dao.create(new_favorite)
            if result:
                log_debug(f"用户{user_id}添加收藏题目{question_id}成功")
                return True
            return False
        except Exception as e:
            log_error(f"添加收藏题目时发生错误: {e}")
            return False

    def remove_favorite_question(self, user_id: int, question_id: int) -> bool:
        """
        移除收藏题目
        :param user_id: 用户ID
        :param question_id: 题目ID
        :return: 移除成功返回True，否则返回False
        """
        try:
            result = self.favorite_dao.delete_by_user_and_question(user_id, question_id)
            if result:
                log_debug(f"用户{user_id}移除收藏题目{question_id}成功")
                return True
            return False
        except Exception as e:
            log_error(f"移除收藏题目时发生错误: {e}")
            return False

    def is_question_favorited(self, user_id: int, question_id: int) -> bool:
        """
        检查题目是否已收藏
        :param user_id: 用户ID
        :param question_id: 题目ID
        :return: 已收藏返回True，否则返回False
        """
        try:
            favorite = self.favorite_dao.get_by_user_and_question(user_id, question_id)
            return favorite is not None
        except Exception as e:
            log_error(f"检查题目收藏状态时发生错误: {e}")
            return False